import React, { useState, useEffect, useCallback } from 'react';
import {
    Table,
    Button,
    Space,
    Tag,
    message,
    Popconfirm,
    Card,
    Input,
    Select,
    DatePicker, Tooltip
} from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    SearchOutlined,
    ReloadOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { taskService } from '../../services/taskService';
import { getCurrentUser } from '../../utils/auth';
import { PRIORITY_MAPPING } from '../../constants/priorityConstants';

const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;


// 定义状态映射
const STATUS_MAPPING = {
    'NOT_STARTED': { text: '待开始', color: 'default' },
    'IN_PROGRESS': { text: '进行中', color: 'processing' },
    'COMPLETED': { text: '已完成', color: 'success' },
    'CANCELLED': { text: '已取消', color: 'error' }
};

const TaskList = () => {
    const [tasks, setTasks] = useState([]);
    const [loading, setLoading] = useState(false);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    });
    const [filters, setFilters] = useState({
        search: '',
        status: '',
        priority: '',
        dateRange: null
    });

    const navigate = useNavigate();
    const currentUser = getCurrentUser();

    // 获取任务列表
    const fetchTasks = useCallback(async (params = {}) => {
        setLoading(true);
        try {
            //console.log('Fetching tasks with params:', params);

            const queryParams = {
                page: pagination.current - 1,
                size: pagination.pageSize,
                ...filters,
                ...params
            };

            // 处理日期范围筛选
            if (filters.dateRange && filters.dateRange.length === 2) {
                queryParams.startDate = filters.dateRange[0]?.toISOString();
                queryParams.endDate = filters.dateRange[1]?.toISOString();
                delete queryParams.dateRange;
            }

            //console.log('Final query params:', queryParams);

            const response = await taskService.getTasks(queryParams);
            //console.log('API response:', response);

            // 正确提取嵌套的数据结构
            let tasksData = [];

            // 处理 response.data.data 格式 (您的实际响应格式)
            if (response?.data?.data && Array.isArray(response.data.data)) {
                tasksData = response.data.data;
                //console.log('Extracted tasks from response.data.data:', tasksData);
            }
            // 处理 response.data 是数组的情况
            else if (Array.isArray(response?.data)) {
                tasksData = response.data;
                //console.log('Extracted tasks from response.data array:', tasksData);
            }

            //console.log('Final tasks data:', tasksData);

            setTasks(tasksData);
            setPagination(prev => ({
                ...prev,
                total: tasksData.length // 或使用后端返回的总数，如果有
            }));
        } catch (error) {
            //console.error('Error fetching tasks:', error);
            message.error('获取任务列表失败');
            setTasks([]);
        } finally {
            setLoading(false);
        }
    }, [pagination.current, pagination.pageSize, filters]);

    // 初始加载和分页变化时重新加载数据
    useEffect(() => {
        fetchTasks();
    }, [fetchTasks]);

    // 删除任务
    const handleDelete = async (id) => {
        try {
            await taskService.deleteTask(id);
            message.success('删除成功');
            fetchTasks();
        } catch (error) {
            message.error('删除失败');
        }
    };

    // 在 TaskList.js 中
    const handleStatusChange = async (id, status) => {
        try {
            const response = await taskService.updateTaskStatus(id, status);

            // 检查响应中的 success 字段
            if (response.data && response.data.success) {
                message.success(response.data.message || '状态更新成功');
                fetchTasks();
            } else {
                message.error(response.data?.message || '状态更新失败');
            }
        } catch (error) {
            //console.error('Error updating task status:', error);
            message.error(error.response?.data?.message || '状态更新失败');
        }
    };

    // 搜索
    const handleSearch = () => {
        setPagination(prev => ({ ...prev, current: 1 }));
        fetchTasks();
    };

    // 更新筛选条件
    const handleFilterChange = (key, value) => {
        setFilters(prev => ({ ...prev, [key]: value }));
    };

    // 重置筛选条件
    const handleResetFilters = () => {
        setFilters({
            search: '',
            status: '',
            priority: '',
            dateRange: null
        });
        setPagination(prev => ({ ...prev, current: 1 }));
        fetchTasks();
    };

    // 表格列定义
    const columns = [
        {
            title: '任务标题',
            dataIndex: 'title',
            key: 'title',
            ellipsis: true,
            render: (text, record) => (
                <a onClick={() => navigate(`/tasks/${record.id}`)}>{text}</a>
            )
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
            ellipsis: true,
            width: 200,
            render: (text) => text || '-'
        },
        {
            title: '优先级',
            dataIndex: 'priority',
            key: 'priority',
            render: (priority) => {
                const priorityInfo = PRIORITY_MAPPING[priority] || { text: '未设置', color: 'default' };
                return <Tag color={priorityInfo.color}>{priorityInfo.text}</Tag>;
            },
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status, record) => {
                const statusInfo = STATUS_MAPPING[status] || { text: status, color: 'default' };
                return (
                    <Select
                        value={status}
                        style={{ width: 120 }}
                        onChange={(value) => handleStatusChange(record.id, value)}
                    >
                        <Option value="NOT_STARTED">待开始</Option>
                        <Option value="IN_PROGRESS">进行中</Option>
                        <Option value="COMPLETED">已完成</Option>
                        <Option value="CANCELLED">已取消</Option>
                    </Select>
                );
            },
        },
        {
            title: '创建时间',
            dataIndex: 'createdAt',
            key: 'createdAt',
            render: (date) => date ? new Date(date).toLocaleDateString() : '-',
        },
        {
            title: '截止时间',
            dataIndex: 'expectedEndDate',
            key: 'expectedEndDate',
            render: (date) => date ? new Date(date).toLocaleDateString() : '-',
        },
        {
            title: '操作',
            key: 'action',
            width: 120, // 设置固定宽度
            render: (_, record) => (
                <Space size="small">
                    <Tooltip title="查看">
                        <Button
                            type="link"
                            icon={<EyeOutlined />}
                            onClick={() => navigate(`/tasks/${record.id}`)}
                        />
                    </Tooltip>
                    <Tooltip title="编辑">
                        <Button
                            type="link"
                            icon={<EditOutlined />}
                            onClick={() => navigate(`/tasks/edit/${record.id}`)}
                        />
                    </Tooltip>
                    <Tooltip title="删除">
                        <Popconfirm
                            title="确定要删除这个任务吗？"
                            onConfirm={() => handleDelete(record.id)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button
                                type="link"
                                danger
                                icon={<DeleteOutlined />}
                            />
                        </Popconfirm>
                    </Tooltip>
                </Space>
            ),
        },
    ];

    return (
        <Card
            title="任务管理"
            extra={
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={() => navigate('/tasks/new')}
                >
                    新建任务
                </Button>
            }
        >
            <Space direction="vertical" style={{ width: '100%' }} size="middle">
                {/* 筛选和搜索 */}
                <Space wrap>
                    <Search
                        placeholder="搜索任务标题或描述"
                        allowClear
                        style={{ width: 250 }}
                        value={filters.search}
                        onChange={(e) => handleFilterChange('search', e.target.value)}
                        onSearch={handleSearch}
                        enterButton={<SearchOutlined />}
                    />

                    <Select
                        placeholder="状态筛选"
                        allowClear
                        style={{ width: 120 }}
                        value={filters.status}
                        onChange={(value) => handleFilterChange('status', value)}
                    >
                        <Option value="NOT_STARTED">待开始</Option>
                        <Option value="IN_PROGRESS">进行中</Option>
                        <Option value="COMPLETED">已完成</Option>
                        <Option value="CANCELLED">已取消</Option>
                    </Select>

                    <Select
                        placeholder="优先级筛选"
                        allowClear
                        style={{ width: 120 }}
                        value={filters.priority}
                        onChange={(value) => handleFilterChange('priority', value)}
                    >
                        <Option value="2">高</Option>
                        <Option value="1">中</Option>
                        <Option value="0">低</Option>
                    </Select>

                    <RangePicker
                        placeholder={['开始日期', '结束日期']}
                        value={filters.dateRange}
                        onChange={(dates) => handleFilterChange('dateRange', dates)}
                    />

                    <Button type="primary" onClick={handleSearch}>
                        搜索
                    </Button>

                    <Button onClick={handleResetFilters} icon={<ReloadOutlined />}>
                        重置
                    </Button>
                </Space>

                {/* 任务表格 */}
                <Table
                    columns={columns}
                    dataSource={tasks}
                    rowKey="id"
                    loading={loading}
                    pagination={{
                        ...pagination,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total, range) =>
                            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                        onChange: (page, pageSize) => {
                            setPagination(prev => ({
                                ...prev,
                                current: page,
                                pageSize
                            }));
                        },
                    }}
                />
            </Space>
        </Card>
    );
};

export default TaskList;
